<?php

namespace app\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Db;
use app\model\Site;
use think\facade\Session;
use think\facade\Request;
use app\utils\Utils;
use app\model\User;
use app\facade\Post;
use Throwable;
use app\utils\DataCache;
use think\helper\Arr;

/**
 * 易混淆词
 * 
 * 社区（整体）
 * └ 帖子（与社区有关系的）
 *   └ 评论（与帖子有关系的）
 *     └ 回复（与评论有关系的）
 */

class Shequ extends BaseController
{
    static public function index($p = 1) // 页面
    {
        $lines = count(Db::connect()->table('site_post')->select()->toArray());
        $posts = Db::connect()->table('site_post')->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'goods' => 'desc', 'time' => 'desc', 'views' => 'desc'])->page(intval($p), 5)->select()->toArray(); // 查询帖子数据
        $result = array();

        foreach ($posts as $key) {
            $user_id = $key['user_id'];
            $userinfo = User::where('id', $user_id)->select()->toArray()[0]; // 查询数据
            $key["user_img"] = $userinfo['img'];
            $key["user_id"] = $user_id;
            $key["user_name"] = $userinfo['name'];
            $result[] = $key;
        }

        $pages = intval($lines / 20);
        if ($lines % 20 != 0) {
            $pages += 1;
        }

        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $user_info = Utils::user($email, $pw);

        return View::fetch(Site::get("template") . '/shequ', [
            'img'  => Site::get("img"),
            'title' => Site::get("title"),
            'about' => Site::get('about'),
            'navitems' => Site::get('navitems'),
            'user_name' => $user_info["name"],
            'user_email' => $user_info["email"],
            'user_img' => $user_info["img"],
            'header' => Site::get("header"),
            'footer' => Site::get("footer"),
            'footer_about' => Site::get("footer_about"),
            'footer_list' => Site::get('footer_list'),
            'post' => $result,
            'lines' => $lines,
            'user_id' => $user_info["id"],
            'pages' => $pages,
            'url' => Site::get("url"),
            'logo' => Site::get("logo")
        ]);
    }

    static public function send_post() // 发送帖子
    {
        $code = 200;
        $value = null;
        $msg = "发送成功";

        $ip = Utils::getIp();

        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        if (Request::isPost()) {
            if ($my_user_info['id'] == '') { //未登录
                $code = 403;
                $msg = '请先登录';
            } else {
                //已登录
                if (Request::post('title') && Request::post('markdown')) {
                    $x = mb_strlen(Request::post('title'));
                    if (intval($x) < 100) {
                        try {
                            $mdtext = Request::post('markdown');
                            $md_original = base64_decode($mdtext);
                            $md_base = $md_original;
                            $md_base = Utils::en_emoji($md_base); //将emoji转换为html
                            $x = mb_strlen($md_base);
                            if ($x < 100000) {
                                if (Post::hasPost(Request::post('title')) || Post::hasSameContentPost($md_base)) {
                                    // 已含有该标题或内容
                                    $code = 406;
                                    $msg = '请勿重复发帖';
                                } else {
                                    if (!Post::hasPartition(intval(Request::post('partition_id', 1)))) {
                                        $code = 401;
                                        $msg = '不存在该分区';
                                    } else {
                                        // 允许发帖
                                        $img = Request::post('img', '');

                                        $data = [
                                            'user_id' => $my_user_info['id'],
                                            'title' => Request::post('title'),
                                            'text' => $md_base,
                                            'time' => time(),
                                            'ip' => $ip,
                                            'goods' => 0,
                                            'views' => 0,
                                            'likes' => 0,
                                            'ishot' => 0,
                                            'ison' => 0,
                                            'isbest' => 0,
                                            'img' => $img,
                                            'post_partition' => intval(Request::post('partition_id', 1))
                                        ];

                                        $value = Post::SavePost($data);
                                    }
                                }
                            } else {
                                $code = 403;
                                $msg = '字数过多';
                            }
                        } catch (Throwable $e) {
                            $code = 401;
                            $msg = '参数有误';
                        }
                    } else {
                        $code = 403;
                        $msg = '字数过多';
                    }
                } else {
                    $code = 401;
                    $msg = '缺少标题或内容';
                }
            }
        }


        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function send_talk() // 发送评论/回复
    {
        $user = Utils::user(Session::get('email'), Session::get('password'));
        if (!$user) {
            return json(['code' => 403, 'msg' => '请先登录']);
        }

        $ip   = Utils::getIp();
        $time = time();
        $text = Utils::en_emoji(Request::post('text', ''));
        if ($text === '') {
            return json(['code' => 401, 'msg' => '缺少内容']);
        }

        /* ---------- 1. 场景路由 ---------- */
        $postId = Request::post('post_id', 0);
        $talkId = Request::post('talk_id', 0);

        /* ---------- 2. 帖子评论 ---------- */
        if ($postId) {
            $post = Post::find($postId);
            if (!$post) {
                return json(['code' => 404, 'msg' => '帖子不存在']);
            }
            if (Db::name('site_talk')->where('post_id', $postId)->where('user_id', $user['id'])->count() >= 15) {
                return json(['code' => 403, 'msg' => '评论数量已满']);
            }
            if (mb_strlen($text) > 200) {
                return json(['code' => 403, 'msg' => '字数过多']);
            }
            $newId = Db::name('site_talk')->insertGetId([
                'user_id' => $user['id'],
                'text' => $text,
                'time' => $time,
                'ip' => $ip,
                'post_id' => $postId
            ]);
            $targetUserId = $post['user_id'];   // 被通知人
            $pushPostId   = $postId;
        }
        /* ---------- 3. 评论回复 ---------- */ elseif ($talkId) {
            $parent = Db::name('site_talk')->find($talkId);
            if (!$parent) {
                return json(['code' => 404, 'msg' => '评论不存在']);
            }
            if (mb_strlen($text) > 150) {
                return json(['code' => 403, 'msg' => '字数过多']);
            }
            $newId = Db::name('site_talk')->insertGetId([
                'user_id' => $user['id'],
                'text' => $text,
                'time' => $time,
                'ip' => $ip,
                'talk_id' => $talkId,
                'post_id' => $parent['post_id']
            ]);
            $targetUserId = $parent['user_id'];
            $pushPostId   = $parent['post_id'];
        } else {
            return json(['code' => 404, 'msg' => '缺少目标']);
        }

        /* ---------- 4. 构造返回 & 通知 ---------- */
        $row = Db::name('site_talk')->find($newId);
        $row['text'] = Utils::html_entity_to_emoji($row['text']);
        $row['img']  = User::where('id', $row['user_id'])->value('img');
        $row['name'] = User::where('id', $row['user_id'])->value('name');

        Utils::send_message(
            $targetUserId,
            $time,
            $user['id'],
            json_encode(['type' => 'talk', 'text' => $text, 'post_id' => $pushPostId])
        );

        return json(['code' => 200, 'msg' => '发送成功', 'data' => $row]);
    }

    static public function get_user($i)
    {
        $data_cache = DataCache::read('shequ_get_user|' . $i);
        if ($data_cache != false) {
            $code = 200;
            $value = null;
            $msg = "获取成功";
            $value = $data_cache;
        } else {
            $user = User::where('id', $i)->select()->toArray(); // 查询用户的数据

            $group = Db::table('site_user_group_user_list')->where('user_id', $i)->select()->toArray();
            // 查询用户组的数据
            $groupItems = array();
            foreach ($group as $item) {
                $groupItem = Db::table('site_user_group')->where('id', $item['group_id'])->select()->toArray();
                $groupItems[] = array(
                    "id" => $groupItem[0]['id'],
                    "title" => $groupItem[0]['title']
                );
            }

            $code = 200;
            $value = null;
            $msg = "获取成功";

            if (count($user) == 0) { // 没有数据
                $code = 404;
                $value = null;
                $msg = "用户不存在";
            } else {
                $code = 200;
                $value = array(
                    'id' => $i,
                    'name' => $user[0]['name'],
                    'img' => $user[0]['img'],
                    'group' => $groupItems
                );
                DataCache::write('shequ_get_user|' . $i, $value, 20);
            }
        }

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function get_post($i) // 获取帖子
    {
        $code = 200;
        $value = null;
        $msg = "获取成功";

        $data_cache = DataCache::read('shequ_get_post|' . $i);
        if ($data_cache != false) {
            $code = 200;
            $msg = "获取成功";
            $value = $data_cache;
            $posts = Db::connect()->table('site_post')->where('id', $i)->select()->toArray(); // 查询帖子的数据
            if (count($posts) == 0) {
                $code = 404;
                $value = null;
                $msg = "帖子不存在";
                $re = array(
                    "code" => $code,
                    'msg' => $msg
                );
                return json($re);
            }
            $c_goods = count(Db::connect()->table('site_goods')->where('post_id', $i)->select()->toArray());

            $email = Session::get('email', '');
            $pw = Session::get('password', '');
            $my_user_info = Utils::user($email, $pw);

            $value['views'] = intval($posts[0]['views']) + 1;
            $value['goods'] = $c_goods; // 贴子点赞
            if ($email == '') {
                $value['is_goods'] = false;
            } else {
                if ($my_user_info['id'] == '') {
                    //未登录
                    $value['is_goods'] = false;
                } else {
                    //已登录
                    $goods = Db::connect()->table('site_goods')->where(['user_id' => $my_user_info['id'], 'post_id' => $i])->select()->toArray(); // 查询数据
                    if (count($goods) == 0) { // 没有点赞
                        $value['is_goods'] = false;
                    } else {
                        $value['is_goods'] = true;
                    }
                }
            }
        } else {
            $posts = Db::connect()->table('site_post')->where('id', $i)->select()->toArray(); // 查询帖子的数据
            $c_goods = count(Db::connect()->table('site_goods')->where('post_id', $i)->select()->toArray());
            if (count($posts) == 0) { // 没有数据
                $code = 404;
                $msg = "帖子不存在";
            } else {
                $value = array(
                    'id' => $i,
                    'title' => $posts[0]['title'],
                    'text' => $posts[0]['text'], // 帖子内容
                    'img' => $posts[0]['img'],
                    'user_id' => $posts[0]['user_id'],
                    'is_hot' => $posts[0]['ishot'] == 1,
                    'is_on' => $posts[0]['ison'] == 1,
                    'is_best' => $posts[0]['isbest'] == 1,
                    'time' => $posts[0]['time']
                );

                //$user = User::where('id', $posts[0]['user_id'])->select()->toArray(); // 查询数据

                $email = Session::get('email', '');
                $pw = Session::get('password', '');
                $my_user_info = Utils::user($email, $pw);


                if ($posts[0]['user_id'] != $my_user_info['id'] && $posts[0]['ban'] == 1) {
                    //尽自己可见
                    $code = 404;
                    $value = null;
                    $msg = "帖子不存在";
                    $re = array(
                        "code" => $code,
                        'msg' => $msg
                    );
                    return json($re);
                } else {
                    DataCache::write('shequ_get_post|' . $i, $value, 10);

                    Db::name('site_post')
                        ->where('id', $i)
                        ->update(['views' => $posts[0]["views"] + 1]); // 增加views
                }

                $value['views'] = $posts[0]['views'] + 1;
                $value['goods'] = $c_goods; // 贴子点赞
                if ($email == '') {
                    $value['is_goods'] = false;
                } else {
                    if ($my_user_info['id'] == '') {
                        //未登录
                        $value['is_goods'] = false;
                    } else {
                        //已登录
                        $goods = Db::connect()->table('site_goods')->where(['user_id' => $my_user_info['id'], 'post_id' => $i])->select()->toArray(); // 查询数据
                        if (count($goods) == 0) { // 没有点赞
                            $value['is_goods'] = false;
                        } else {
                            $value['is_goods'] = true;
                        }
                    }
                }
            }
        }

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function get_talk($i) // 获取评论
    {
        // 设置当前时间
        $now = time();

        // 设置过期时间为1秒后
        $expires = $now + 1;  // 这里的1是指1秒

        // 设置Last-Modified和Expires头
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $now) . ' GMT');
        header('Expires: ' . gmdate('D, d M Y H:i:s', $expires) . ' GMT');

        // 设置Cache-Control头
        header('Cache-Control: max-age=1');  // 这里的1也是指1秒

        $post_id = $i;
        $talks = Db::connect()->table('site_talk')->where('post_id', $post_id)->order('id', 'desc')->select()->toArray(); // 查询帖子的评论数据
        $result = array();

        foreach ($talks as $value) {
            // 对 $value 进行操作
            $user = User::where('id', $value["user_id"])->select()->toArray(); // 查询用户数据
            $talks_talks = Db::connect()->table('site_talk')->where('talk_id', $value["id"])->order('id', 'desc')->select()->toArray(); // 查询评论的评论数据
            $talks_result = array();

            foreach ($talks_talks as $talks_value) { // 遍历得到的评论的回复数据
                $user_talks = User::where('id', $talks_value["user_id"])->select()->toArray(); // 查询每一条评论的用户数据

                $talks_result[] = array(
                    'id' => $talks_value["id"],
                    'text' => Utils::html_entity_to_emoji($talks_value['text']),
                    'img' => $user_talks[0]["img"],
                    'name' => $user_talks[0]["name"],
                    'user_id' => $talks_value["user_id"],
                    'time' => $talks_value['time']
                );
            }

            $result[] = array(
                'id' => $value['id'],
                'text' => Utils::html_entity_to_emoji($value['text']),
                'img' => $user[0]["img"], // 用户头像
                'name' => $user[0]["name"], // 用户名
                'user_id' => $value["user_id"], // 从评论数据中得到的用户ID
                'time' => $value['time'], // 时间
                'talks' => $talks_result // 评论回复
            );
        }

        return json(array(
            'code' => 200,
            'data' => $result,
            'msg' => "获取成功"
        ));
    }

    static public function post($id) // 帖子页面
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        $posts = Db::connect()->table('site_post')->where('id', $id)->select()->toArray(); // 查询数据

        if (count($posts) == 0) { // 没有数据
            http_response_code(404);
            return View::fetch(Site::get('template') . '/404');
        } else {
            if (intval($posts[0]['user_id']) == intval($my_user_info["id"])) { //如果为登录用户的帖子
                $isme = true;
            } else {
                $isme = false;
            }
            $email = Session::get('email', ''); // 读取用户email

            $post_content = $posts[0]['text'];

            $matches = [];
            $first_image = "";
            if (preg_match_all('/\!\[\]\(.+\)/m', $post_content, $matches)) $first_image = $matches[0][0];

            $first_image = preg_replace('/^!\[(.*?)\]\((.*?) \"(.*?)\"\)$/m', '$2', $first_image); // 图片
            $first_image = preg_replace('/^!\[(.*?)\]\((.*?)\)$/m', '$2', $first_image); // 图片

            $post_plain = Utils::markdownToText($post_content);
            $post_describe = mb_substr($post_plain, 0, 160, 'utf-8');

            View::assign([
                'id' => $id,
                'about' => Site::get('about'),
                'title' => Site::get("title"),
                'site_img'  => Site::get("img"),
                'post_title' => $posts[0]['title'],
                'text' => '', //Utils::markdownToHtml($posts[0]['text']),
                'short_text' => mb_substr($posts[0]['text'], 0, 160, 'utf-8'),
                'navitems' => Site::get('navitems'),
                'my_user_name' => $my_user_info["name"],
                'my_user_email' => $my_user_info["email"],
                'my_user_img' => $my_user_info["img"],
                'my_user_id' => $my_user_info["id"],
                'isme' => $isme,
                'logo' => Site::get("logo"),
                'header' => Site::get("header"),
                'footer' => Site::get("footer"),
                'footer_about' => Site::get("footer_about"),
                'footer_list' => Site::get('footer_list'),

                'post_image' => $first_image,
                'post_plain' => $post_describe
            ]);

            return View::fetch(Site::get('template') . '/post');
        }
    }

    static public function setgoods($i) // 点赞
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        $code = 200;
        $value = null;
        $msg = "点赞成功";

        if ($my_user_info['id'] == '') { // 用户鉴权失败
            $code = 403;
            $msg = "请先登录";
        } else {
            $post_id = $i; // 获取post传入的帖子ID

            //$user = User::where('email', $email)->select()->toArray(); // 查询数据

            if ($post_id == '0') { // 没有传递帖子接口导致获取到的是0
                $code = 403;
                $msg = "参数有误";
            } else {
                //数据校验完成
                $userid = $my_user_info['id'];
                $posts = Db::connect()->table('site_post')->where('id', $post_id)->select()->toArray(); // 查询数据

                if (count($posts) == 0) { // 不存在,不允许点赞
                    $code = 404;
                    $msg = "帖子不存在";
                } else { // 存在帖子
                    $goods = Db::connect()->table('site_goods')->where(['user_id' => $userid, 'post_id' => $post_id])->select()->toArray(); // 查询数据

                    if (count($goods) == 0) { // 没有点赞
                        $data = ['user_id' => $userid, 'post_id' => $post_id];
                        Db::name('site_goods')->strict(false)->insert($data);

                        $goods = Db::connect()->table('site_goods')->where(['post_id' => $post_id])->select()->toArray(); // 查询数据
                        Db::name('site_post')
                            ->where('id', $post_id)
                            ->update(['goods' => count($goods)]); // 增加goods

                        $value = count($goods);

                        Utils::send_message(
                            $posts[0]['user_id']/*该帖子的发帖用户 */,
                            time(),
                            $my_user_info['id'],
                            json_encode(
                                array(
                                    'type' => 'good',
                                    'post_id' => $post_id
                                )
                            )
                        );
                    } else {
                        $code = 403;
                        $msg = "已点赞";
                    }
                }
            }
        }

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function unsetgoods($i) // 取消点赞
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        $code = 200;
        $value = null;
        $msg = "取消点赞成功";

        if ($my_user_info['id'] == '') { // 用户鉴权失败
            $code = 403;
            $msg = "请先登录";
        } else {
            $post_id = $i; // 获取post传入的帖子ID
            //$user = Db::table('site_user')->where('email', $email)->select()->toArray(); // 查询数据

            if ($post_id == '0') { // 没有传递帖子接口导致获取到的是0
                $code = 403;
                $msg = "参数有误";
            } else {

                $userid = $my_user_info['id'];
                $posts = Db::table('site_post')->where('id', $post_id)->select()->toArray(); // 查询数据

                if (count($posts) == 0) { // 不存在,不允许撤销点赞
                    $code = 404;
                    $msg = "帖子不存在";
                } else { // 存在帖子
                    $goods = Db::connect()->table('site_goods')->where(['user_id' => $userid, 'post_id' => $post_id])->select()->toArray(); // 查询数据

                    if (count($goods) == 0) { // 没有点赞
                        $code = 403;
                        $msg = "未点赞";
                    } else {
                        Db::table('site_goods')->where(['user_id' => $userid, 'post_id' => $post_id])->delete();

                        $goods = Db::connect()->table('site_goods')->where(['post_id' => $post_id])->select()->toArray(); // 查询数据
                        Db::name('site_post')
                            ->where('id', $post_id)
                            ->update(['goods' => count($goods) - 1]); // 减去goods

                        $value = count($goods) - 1;
                    }
                }
            }
        }

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function sendpost() // 发帖页面
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        return View::fetch(Site::get('template') . '/sendpost', [
            'img' => Site::get('img'),
            'about' => Site::get('about'),
            'title' => Site::get('title'),
            'navitems' => Site::get('navitems'),
            'user_name' => $my_user_info["name"],
            'user_email' => $my_user_info["email"],
            'user_img' => $my_user_info["img"],
            'user_id' => $my_user_info["id"],
            'logo' => Site::get("logo"),
            'about' => Site::get('about'),
            'header' => Site::get("header"),
            'footer' => Site::get("footer"),
            'footer_about' => Site::get("footer_about"),
            'footer_list' => Site::get('footer_list')
        ]);
    }

    static public function get_post_list($p, $i) // 获取帖子列表
    {
        $pagecut = 20;
        header('Content-Type: application/json');

        $code = 200;
        $value = null;
        $msg = "获取成功";

        $data_cache = DataCache::read('shequ_get_post_list|' . $p . $i);
        if ($data_cache != false) {
            $value = $data_cache;
        } else {
            if ($i == 'all') {
                $posts = Db::table('site_post')->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'time' => 'desc', 'goods' => 'desc',  'views' => 'desc'])->page(intval($p), $pagecut)->select()->toArray(); // 查询帖子数据
                $result = array();

                foreach ($posts as $key) {
                    $user_id = $key['user_id'];
                    $userinfo = User::where('id', $user_id)->select()->toArray()[0]; // 查询数据
                    $key["user_img"] = $userinfo['img'];
                    $key["user_id"] = $user_id;
                    $key["user_name"] = $userinfo['name'];
                    $key['text'] = mb_strlen($key['text']) > 100 ? (mb_substr($key['text'], 0, 100, "utf-8") . "...") : $key['text'];
                    unset($key['ip']);
                    $groups = Db::table('site_user_group_user_list')->where('user_id', $user_id)->select()->toArray();
                    $key['user_group'] = array();
                    if (count($groups) > 0) {
                        foreach ($groups as $m) {
                            $key['user_group'][] = Db::table('site_user_group')->where('id', $m['group_id'])->select()->toArray()[0]['title'];
                        }
                    }
                    $result[] = $key;
                }

                $pages = count(Db::connect()->table('site_post')->select()->toArray());
                if ($pages % $pagecut == 0) {
                    $pages = $pages / $pagecut;
                } else {
                    $pages = ceil($pages / $pagecut);
                }

                $value = array("data" => $result, "size" => $pages);
            } else {
                if (count(Db::table('site_post_partition')->where('id', intval($i))->select()->toArray()) == 0) {
                    $code = 401;
                    $msg = '不存在该分区';
                } else {
                    $posts = Db::connect()->table('site_post')->where('post_partition', intval($i))->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'time' => 'desc', 'goods' => 'desc',  'views' => 'desc'])->page(intval($p), $pagecut)->select()->toArray(); // 查询帖子数据
                    $result = array();

                    foreach ($posts as $key) {
                        $user_id = $key['user_id'];
                        $userinfo = User::where('id', $user_id)->select()->toArray()[0]; // 查询数据
                        $key["user_img"] = $userinfo['img'];
                        $key["user_id"] = $user_id;
                        $key["user_name"] = $userinfo['name'];
                        $key['text'] = mb_strlen($key['text']) > 100 ? (mb_substr($key['text'], 0, 100, "utf-8") . "...") : $key['text'];
                        unset($key['ip']);
                        $groups = Db::table('site_user_group_user_list')->where('user_id', $user_id)->select()->toArray();
                        $key['user_group'] = array();
                        if (count($groups) > 0) {
                            foreach ($groups as $m) {
                                $key['user_group'][] = Db::table('site_user_group')->where('id', $m['group_id'])->select()->toArray()[0]['title'];
                            }
                        }
                        $result[] = $key;
                    }

                    $pages = count(Db::connect()->table('site_post')->where('post_partition', intval($i))->select()->toArray());
                    if ($pages % $pagecut == 0) {
                        $pages = $pages / $pagecut;
                    } else {
                        $pages = ceil($pages / $pagecut);
                    }

                    $value = array("data" => $result, "size" => $pages);
                    DataCache::write('shequ_get_post_list|' . $p . $i, $value, 10);
                }
            }
        }

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function get_post_partition() // 获取帖子分区
    {
        header('Content-Type: application/json');

        $partitions = Db::table('site_post_partition')->select()->toArray(); // 查询分区数据

        return Utils::api_response(200, "获取成功", $partitions);
    }

    static public function get_home_post_list() // 获取首页的帖子列表
    {
        header('Content-Type: application/json');

        $code = 200;
        $value = null;
        $msg = "获取成功";

        $posts = Db::table('site_post')->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'time' => 'desc', 'goods' => 'desc', 'views' => 'desc'])->page(1, 3)->select()->toArray(); // 查询帖子数据
        $result = array();

        foreach ($posts as $key) {
            $user_id = $key['user_id'];
            $userinfo = User::where('id', $user_id)->select()->toArray()[0]; // 查询数据
            $key["user_img"] = $userinfo['img'];
            $key["user_id"] = $user_id;
            $key["user_name"] = $userinfo['name'];
            $key['text'] = mb_strlen($key['text']) > 100 ? (mb_substr($key['text'], 0, 100, "utf-8") . "...") : $key['text'];
            unset($key['ip']);
            $result[] = $key;
        }

        $value = $result;

        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function del_post()
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        $post_id = Request::post("post_id", false);

        if ($my_user_info['id'] == '') {
            //未登录
            return json(array('code' => 403, 'msg' => '未登录'));
        }

        if (!$post_id) {
        } else {
            $posts = Db::table('site_post')->where('id', $post_id)->select()->toArray(); // 查询帖子的数据
            if (count($posts) == 0) { // 不存在
                return json(array('code' => 404, 'msg' => '删除失败'));
            } else {
                if (intval($posts[0]['user_id']) == intval($my_user_info['id'])) {
                    Db::table('site_post')->where('id', $post_id)->delete();
                    return json(array('code' => 200, 'msg' => '删除成功'));
                } else {
                    return json(array('code' => 403, 'msg' => '删除失败'));
                }
            }
        }
    }

    static public function search_post($p = 1)
    {
        //搜索帖子
        $pagecut = 20;
        header('Content-Type: application/json');

        $code = 200;
        $value = null;
        $msg = "获取成功";
        $key_word = Request::get("key_word", false);
        if (!$key_word) {
            //缺少关键词
            return json(array("code" => 400, 'msg' => '参数有误'));
        }
        $posts = Db::table('site_post')->where('title|text', 'LIKE', '%' . $key_word . '%')->order(['ison' => 'desc', 'isbest' => 'desc', 'ishot' => 'desc', 'time' => 'desc', 'goods' => 'desc',  'views' => 'desc'])->page(intval($p), $pagecut)->select()->toArray(); // 查询帖子数据
        $result = array();

        foreach ($posts as $key) {
            $user_id = $key['user_id'];
            $userinfo = Db::table('site_user')->where('id', $user_id)->select()->toArray()[0]; // 查询数据
            $key["user_img"] = $userinfo['img'];
            $key["user_id"] = $user_id;
            $key["user_name"] = $userinfo['name'];
            $key['text'] = mb_strlen($key['text']) > 100 ? (mb_substr($key['text'], 0, 100, "utf-8") . "...") : $key['text'];
            unset($key['ip']);
            $result[] = $key;
        }

        $pages = count(Db::table('site_post')->where('title|text', 'LIKE', '%' . $key_word . '%')->select()->toArray());
        if ($pages % $pagecut == 0) {
            $pages = $pages / $pagecut;
        } else {
            $pages = ceil($pages / $pagecut);
        }

        $value = array("data" => $result, "size" => $pages);


        $re = array(
            "code" => $code,
            'msg' => $msg
        );
        if ($code == 200) {
            $re['data'] = $value;
        }
        return json($re);
    }

    static public function change_post($p)
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);
        $post_id = $p;

        if ($my_user_info['id'] == '') {
            //未登录
            return View::fetch(Site::get('template') . '/404');
        } else {
            //登录鉴权完毕
            $posts = Db::table('site_post')->where('id', $post_id)->select()->toArray(); // 查询帖子的数据
            if (count($posts) == 0) { // 不存在
                return View::fetch(Site::get('template') . '/404');
            } else {
                if (intval($posts[0]['user_id']) == intval($my_user_info['id'])) {
                    //权限鉴定完成
                    return View::fetch(Site::get('template') . '/changepost', [
                        'img' => Site::get('img'),
                        'about' => Site::get('about'),
                        'title' => Site::get('title'),
                        'logo' => Site::get('logo'),
                        'navitems' => Site::get('navitems'),
                        'user_name' => $my_user_info["name"],
                        'user_email' => $my_user_info["email"],
                        'user_img' => $my_user_info["img"],
                        'user_id' => $my_user_info["id"],
                        'about' => Site::get('about'),
                        'header' => Site::get("header"),
                        'footer' => Site::get("footer"),
                        'footer_about' => Site::get("footer_about"),
                        'footer_list' => Site::get('footer_list')
                    ]);
                } else {
                    //无权限
                    return View::fetch(Site::get('template') . '/404');
                }
            }
        }
    }

    static public function change_post_api()
    {
        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);
        $post_id = Request::post('post_id', false);

        if ($my_user_info['id'] == '') {
            //未登录
            return json(array('code' => 403, 'msg' => '参数有误'));
        } else {
            //登录鉴权完毕
            $posts = Db::table('site_post')->where('id', $post_id)->select()->toArray(); // 查询帖子的数据
            if (count($posts) == 0) { // 不存在
                return json(array('code' => 404, 'msg' => '帖子不存在'));
            } else {
                if (intval($posts[0]['user_id']) == intval($my_user_info['id'])) {
                    //权限鉴定完成
                    $title = Request::post('title', false);
                    $markdown = Request::post('markdown', false);
                    $partition_id = Request::post('partition_id', 1);
                    if (!$title || !$markdown || !$partition_id || !$post_id) { //缺少参数
                        return json(array('code' => 404, 'msg' => '参数有误'));
                    } else {
                        //参数完整
                        $x = mb_strlen($title);
                        if (intval($x) < 100) {
                            //字数符合要求
                            try {
                                $mdtext = $markdown;
                                $md_original = base64_decode($mdtext);
                                $md_base = $md_original;
                                $x = mb_strlen($md_base);
                                if ($x < 100000) {

                                    if (!Post::hasPartition(intval($partition_id))) {
                                        $code = 401;
                                        $msg = '不存在该分区';
                                    } else {
                                        // 允许发帖
                                        $img = Request::post('img', '');

                                        $data = [
                                            'title' => Request::post('title'),
                                            'text' => $md_base,
                                            'img' => $img,
                                            'time' => time(),
                                            'post_partition' => intval(Request::post('partition_id', 1))
                                        ];

                                        Post::ChangePost($post_id, $data);
                                        $code = 200;
                                        $msg = '修改成功';
                                        return json(array('code' => $code, 'msg' => $msg, 'data' => $post_id));
                                    }
                                } else {
                                    $code = 403;
                                    $msg = '字数过多';
                                }
                            } catch (Throwable $e) {
                                $code = 401;
                                $msg = '请求参数有误';
                            }
                        } else {
                            $code = 403;
                            $msg = '标题字数过多';
                        }
                    }
                    return json(array('code' => $code, 'msg' => $msg));
                } else {
                    //无权限
                    return json(array('code' => 403, 'msg' => '修改失败'));
                }
            }
        }
    }
}
